package com.oromwin.repos.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.http.handler.TestHandler;
import com.sun.net.httpserver.HttpServer;

public class ReposHttpServer {
    private static Log log = Logger.getLog(ReposHttpServer.class);

    private HttpServer server = null;

    public long startUpTimestamp = System.currentTimeMillis();
    public int warnCount = 0;
    public int errorCount = 0;
    public long receiveBytes = 0;
    public long sendBytes = 0;
    public int flushHandlerCallCount = 0;
    public final static int PORT = 5000;

    public ReposHttpServer() throws ReposException {
        try {
            this.server = HttpServer.create(new InetSocketAddress(PORT), PORT);
        } catch (IOException e) {
            throw ReposException.create(log, e.getMessage());
        }
        server.createContext("/test", new TestHandler());
        this.server.setExecutor(Executors.newFixedThreadPool(10));
    }

    public void start() {
        if (log.isInfoEnabled()) log.info("Start deamon.");
        this.server.start();
    }

    public void stop(int exitCode) {
        if (log.isInfoEnabled()) log.info("Stop deamon.");
        this.server.stop(exitCode);
    }

    @Override
    public void finalize() {
        if (log.isInfoEnabled()) log.info("Shutdown deamon.");
    }
}
